package com.lagou.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author jinshanzhang
 * @version 1.0
 * @description
 * @date 2021/11/1 5:01 下午
 */
@Configuration
public class RabbitConfig {

    /**
     * 声明支付延时队列
     * @return
     */
    @Bean
    public Queue payWaitingQueue(){
        Map<String, Object> props = new HashMap<>();
        // 设置队列TTL
        props.put("x-message-ttl", 10000);
        // 设置该队列所关联的死信交换器（当队列消息TTL到期后依然没有消费，则加入死信队列）
        props.put("x-dead-letter-exchange", "exchange.pay.waiting.dlx");
        // 设置该队列所关联的死信交换器的routingKey，如果没有特殊指定，使用原队列的 routingKey
        props.put("x-dead-letter-routing-key", "pay.waiting.dlx");
        Queue queue = new Queue("queue.pay.waiting", false, false, false, props);
        return queue;
    }


    /**
     * 声明支付延时交换器
     * @return
     */
    @Bean
    public Exchange payWaitingExchange(){
        DirectExchange exchange = new DirectExchange("exchange.pay.waiting", false, false);
        return exchange;
    }

    /**
     * 绑定队列和交换器
     * @return
     */
    @Bean
    public Binding bindingQueueAndExchange(){
        return BindingBuilder.bind(payWaitingQueue()).to(payWaitingExchange()).with("pay.waiting").noargs();
    }

    /**
     * 声明死信队列
     * @return
     */
    @Bean
    public Queue payWaitingDlxQueue(){
        Queue queue = new Queue("queue.pay.waiting.dlx", false, false, false, null);
        return queue;
    }

    /**
     * 声明死信交换器
     * @return
     */
    @Bean
    public Exchange payWaitingDlxExchange(){
        DirectExchange exchange = new DirectExchange("exchange.pay.waiting.dlx", false, false);
        return exchange;
    }

    /**
     * 绑定死信队列和死信交换器
     * @return
     */
    @Bean
    public Binding bindingDlxExchangeAndQueue(){
        return BindingBuilder.bind(payWaitingDlxQueue()).to(payWaitingDlxExchange()).with("pay.waiting.dlx").noargs();
    }
}
